package com.wctj.api.business.common.service;

import com.wctj.api.base.enums.PayModeEnums;
import com.wctj.api.infra.common.bean.NoticeParams;
import com.wctj.api.infra.common.bean.NoticeRequest;
import com.wctj.api.infra.web.support.HttpRequestNoticeParams;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.TreeMap;

/**
 * 支付回调响应模式处理
 */
public interface PayResponse {

    /**
     * 对 HTTP 回调参数进行签名验证
     * @param noticeParams
     * @return
     */
    Boolean validResponse(NoticeParams noticeParams);

    /**
     * 处理回调请求
     * @param requestNoticeParam
     * @return
     */
    String handle(HttpRequestNoticeParams requestNoticeParam);

    default String handle(HttpRequestNoticeParams requestNoticeParam,String payMode){
        return handle(requestNoticeParam);
    };

    /**
     * 将请求参数或者请求流转化为 Map
     *
     * @param request 通知请求
     * @return 获得回调的请求参数
     */
    default <P extends NoticeParams> P getNoticeParams(NoticeRequest request){
        final Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String, Object> params = new TreeMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            StringBuilder sb = new StringBuilder();
            for (int i = 0, len = values.length; i < len; i++) {
                sb.append(values[i]).append((i == len - 1) ? "" : ',');
            }
            // 默认都是 UTF-8
            String valueStr = sb.toString();
            params.put(name, valueStr);
        }
        return (P) new NoticeParams(params);
    }

    @Transactional(rollbackFor = Exception.class)
    default void payBack(NoticeParams noticeParams, String payOrderNum) {
    }

    /**
     * 支付模式
     * @return
     */
    PayModeEnums getPayMode();



}
